﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileMonitor.Provider;
using System.IO;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using FileMonitor.Provider.FileMonitor;
using FileUtility;
using System.Data.SqlClient;

namespace TXTFileMonitor
{
    public class Process : FileMonitorBase
    {
        // Methods
        public override void ProcessChanged(FileSystemEventArgs e)
        {
        }

        public override void ProcessCreated(FileSystemEventArgs e)
        {
            try
            {
                string name = e.Name;
                string s = string.IsNullOrEmpty(base.AllConfig["PlantCodeIndex"]) ? "0" : base.AllConfig["PlantCodeIndex"];
                string str3 = string.IsNullOrEmpty(base.AllConfig["PlantCodeLength"]) ? "4" : base.AllConfig["PlantCodeLength"];
                string plantCode = e.Name.Substring(int.Parse(s), int.Parse(str3));
                string connectionString = Utility.ReadDBNameByPlant(base.exchangeDB, plantCode);
                SqlDatabase targetExchangDB = null;
                if (string.IsNullOrEmpty(connectionString))
                {
                    connectionString = base.exchangeDB.CreateConnection().ConnectionString;
                }
                targetExchangDB = new SqlDatabase(connectionString);
                string str6 = base.AllConfig["FilterPlantCode"];
                string splitChar = base.AllConfig["SplitChar"];
                if (string.IsNullOrEmpty(str6))
                {
                    this.ProcessFile(name, e.FullPath, splitChar, targetExchangDB);
                }
                else
                {
                    string[] strArray = str6.Split(",".ToCharArray());
                    if (strArray != null)
                    {
                        if (strArray.Length == 0)
                        {
                            this.ProcessFile(name, e.FullPath, splitChar, base.exchangeDB);
                        }
                    }
                    else
                    {
                        this.ProcessFile(name, e.FullPath, splitChar, base.exchangeDB);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }

        public override void ProcessDeleted(FileSystemEventArgs e)
        {
        }

        private void ProcessFile(string filename, string filePath, string splitChar, SqlDatabase targetExchangDB)
        {
            string str4;
            int num;
            int num2;
            DataTable dataTableNoData = Utility.GetDataTableNoData(base.exchangeDB, base.AllConfig["TargetTable"]);
            string s = string.IsNullOrEmpty(base.AllConfig["PlantCodeIndex"]) ? "0" : base.AllConfig["PlantCodeIndex"];
            string str2 = string.IsNullOrEmpty(base.AllConfig["PlantCodeLength"]) ? "4" : base.AllConfig["PlantCodeLength"];
            string plantCode = filename.Substring(int.Parse(s), int.Parse(str2));
            if (filename.IndexOf("(") > 0)
            {
                str4 = filename.Substring(0, filename.LastIndexOf("("));
                string str5 = filename.Substring(filename.LastIndexOf("(") + 1, (filename.LastIndexOf(")") - filename.LastIndexOf("(")) - 1);
                num = int.Parse(str5.Substring(0, str5.IndexOf("_")));
                num2 = int.Parse(str5.Substring(str5.IndexOf("_"), str5.Length - str5.IndexOf("_")).TrimStart("_".ToCharArray()));
            }
            else
            {
                str4 = filename.Substring(0, filename.LastIndexOf("."));
                num = 1;
                num2 = 1;
            }
            bool isNew = true;
            Guid batchId = Utility.GetBatchID("Forecast", base.exchangeDB, "TransferLogT", str4, out isNew);
            if (isNew)
            {
                num2 = 0;
                Utility.AddNewFileLog(targetExchangDB, batchId, base.AllConfig["DataType"], base.AllConfig["MonitorPath"], str4, num, num2, 0, -1, plantCode);
            }
            try
            {
                DataTable table = Utility.ReadFileContentToDataTable(filePath, dataTableNoData, batchId, splitChar);
                SqlBulkCopy copy = new SqlBulkCopy(targetExchangDB.CreateConnection().ConnectionString, SqlBulkCopyOptions.UseInternalTransaction);
                copy.DestinationTableName = base.AllConfig["TargetTable"];
                copy.BulkCopyTimeout = 360;
                if (!string.IsNullOrEmpty(base.AllConfig["DataFilter"]))
                {
                    copy.WriteToServer(table.Select(base.AllConfig["DataFilter"]));
                    Utility.AddFileCount(targetExchangDB, batchId, table.Select(base.AllConfig["DataFilter"]).Length);
                }
                else
                {
                    copy.WriteToServer(table);
                    Utility.AddFileCount(targetExchangDB, batchId, table.Rows.Count);
                }
            }
            catch (Exception exception)
            {
                Utility.SaveException(targetExchangDB, batchId, exception.Message, filename);
                throw new Exception(exception.Message);
            }
        }
    }

}
